#!/user/bin/env python3
# -*- coding: utf-8 -*-
import os
import glob
import shutil
from bs4 import BeautifulSoup
import xml.etree.ElementTree as ET
from xml.dom import minidom

def clear_folder(folder_path):
    """清空指定文件夹中的所有文件"""
    if os.path.exists(folder_path):
        for filename in os.listdir(folder_path):
            file_path = os.path.join(folder_path, filename)
            try:
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            except Exception as e:
                print(f'删除 {file_path} 时出错: {e}')
        print(f'已清空文件夹: {folder_path}')

def html_to_xml(html_file_path, xml_file_path):
    """将HTML文件转换为XML文件"""
    try:
        # 读取HTML文件
        with open(html_file_path, 'r', encoding='utf-8') as f:
            html_content = f.read()
        
        # 使用BeautifulSoup解析HTML
        soup = BeautifulSoup(html_content, 'html.parser')
        
        # 创建XML根元素
        root = ET.Element('document')
        
        # 添加文档信息
        filename = os.path.splitext(os.path.basename(html_file_path))[0]
        root.set('name', filename)
        
        # 遍历HTML中的所有元素并转换为XML
        body = soup.find('body')
        if body:
            convert_html_to_xml(body, root)
        
        # 格式化XML输出
        xml_str = ET.tostring(root, encoding='unicode')
        dom = minidom.parseString(xml_str)
        pretty_xml = dom.toprettyxml(indent='  ', encoding=None)
        
        # 移除空行
        lines = [line for line in pretty_xml.split('\n') if line.strip()]
        formatted_xml = '\n'.join(lines)
        
        # 写入XML文件
        with open(xml_file_path, 'w', encoding='utf-8') as f:
            f.write(formatted_xml)
        
        print(f'{xml_file_path}')
        return True
        
    except Exception as e:
        print(f'转换失败 {html_file_path}: {e}')
        return False

def convert_html_to_xml(html_element, xml_parent):
    """递归转换HTML元素为XML元素"""
    for child in html_element.children:
        if hasattr(child, 'name') and child.name:
            # 创建XML元素
            xml_element = ET.SubElement(xml_parent, child.name)
            
            # 复制属性
            if hasattr(child, 'attrs'):
                for attr_name, attr_value in child.attrs.items():
                    if isinstance(attr_value, list):
                        attr_value = ' '.join(attr_value)
                    xml_element.set(attr_name, str(attr_value))
            
            # 处理直接文本内容（不包括子元素的文本）
            if child.string and child.string.strip():
                xml_element.text = child.string.strip()
            elif child.get_text(strip=True) and not list(child.children):
                # 如果没有子元素，获取所有文本内容
                xml_element.text = child.get_text(strip=True)
            
            # 递归处理子元素
            convert_html_to_xml(child, xml_element)
        
        elif hasattr(child, 'strip') and child.strip():
            # 处理纯文本节点（只有当父元素没有其他子元素时才添加）
            text_content = child.strip()
            if text_content and not xml_parent.text:
                xml_parent.text = text_content

def batch_convert_html_to_xml():
    """批量转换HTML文件为XML文件"""
    html_folder = 'html'
    xml_folder = 'xml'
    
    # 清空xml输出文件夹
    clear_folder(xml_folder)
    
    # 创建xml输出文件夹
    if not os.path.exists(xml_folder):
        os.makedirs(xml_folder)
        print(f'创建输出文件夹: {xml_folder}')
    
    # 获取所有HTML文件
    html_files = glob.glob(os.path.join(html_folder, '*.html'))
    
    if not html_files:
        print(f'在 {html_folder} 文件夹中未找到HTML文件')
        return
    
    print(f'找到 {len(html_files)} 个HTML文件')
    
    success_count = 0
    
    # 批量转换
    for html_file in html_files:
        filename = os.path.splitext(os.path.basename(html_file))[0]
        xml_file = os.path.join(xml_folder, f'{filename}.xml')
        
        if html_to_xml(html_file, xml_file):
            success_count += 1
    
    print(f'\n成功转换 {success_count}/{len(html_files)} 个文件')

if __name__ == '__main__':
    batch_convert_html_to_xml()